export const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}

const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}

/**
 * 拼接路径
 * @param {*} toPath 目标路径
 * @param {*} redirece 是否需要跳转回当前路径
 */
export const splicingPath = (toPath: string, redirece = true) => {
  let redirectData = '';

  if (redirece) {
    // 获取当前路由
    let pageRoute = getPageRoute()?.route || '';

    if (pageRoute) {
      // 重定向参数
      redirectData = `?redirect=/${pageRoute}`;
    }
  }

  // 拼接新路径
  return toPath + redirectData;
};

/**
 * 获取页面当前路由 信息
 * index = 1 则为获取上一个页面路由信息, 以此类推
 * @param {*} index 向上翻的页数
 */
export function getPageRoute(index = 0) {
  const pages = getCurrentPages();
  let currPage = null;
  if (pages.length) {
    currPage = pages[pages.length - 1 - index];
  }
  return currPage;
}

// 同步获取本地数据
export function getStorageSync(key: string) {
  try {
    var value = wx.getStorageSync(key);
    if (value) return value;
  } catch (e) {
    console.error(e);
    wx.showToast({
      title: '获取storage数据失败',
      icon: 'none',
    });
  }

  // 出错或没有找到数据
  return '';
}

// 同步获取存入本地数据
export function saveSync(key: string, value: string) {
  try {
    wx.setStorageSync(key, value);
  } catch (e) {
    console.log(e);
  }
}

export const TOKEN_KEY = 'token'
export function getToken() {
  return getStorageSync(TOKEN_KEY);
}
export function setToken(token: string) {
  saveSync(TOKEN_KEY, token);
}

export function getUserInfo() {
  return getStorageSync('userInfo')
}

export function setUserInfo(userInfo: string) {
  saveSync('userInfo', userInfo);
}

